package com.gray.blog.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * Created  By zhoux 2019/01/10
 **/
@Slf4j
public class JWTUtil {

    // 过期时间为24小时
    private static final long EXPIRE_TIME  = 60 * 24 * 60 * 1000;

    private static final String SECRET = "SHIRO+JWT";

    /**
     * 生成token
     * @param username
     * @return
     */
    public static String createToken(String username) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm =  Algorithm.HMAC256(SECRET);
            // token中存放username信息
            return JWT.create()
                .withClaim("username", username)
                //到期时间
                .withExpiresAt(date)
                //创建一个新的JWT，并使用给定的算法进行标记
                .sign(algorithm);
        } catch (Exception e) {
            log.error("JWTUtil.createToken error username:{}", username);
            return null;
        }
    }

    /**
     * 校验token权限
     * @param token
     * @param username
     * @return
     */
    public static boolean verifyToken(String token, String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //在token中附带了username信息
            JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("username", username)
                .build();
            // 验证token
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取token中信息，无需secret解密
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (Exception e) {
            return null;
        }
    }


}
